﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.DataAccess;
using WLFramework.Json;

namespace SampleSite.admin.ajax.grid
{
    /// <summary>
    /// getAllModules 的摘要说明
    /// </summary>
    public class getAllModules : AjaxHttpHandler
    {
        private class TreeNode
        {
            public int id { get; set; }
            public int app_id { get; set; }
            public int group_id { get; set; }
            public string name { get; set; }
            public string url { get; set; }

            /// <summary>
            /// 1 2 or 3
            /// </summary>
            public int type { get; set; }

            public List<TreeNode> children { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            List<TreeNode> list = new List<TreeNode>();
            using (PermissionContext db = new PermissionContext())
            {
                var cmd = DataAccessor.CreateInstance<PermissionCommand>();
                var apps = db.sys_Applications.Where(k => k.A_State == 1);

                foreach (var app in apps)
                {
                    var modules = cmd.GetModuleByApplication(app.A_ID);
                    list.Add(new TreeNode()
                    {
                        id = -app.A_ID,
                        name = app.A_CName,
                        type = 1,
                        children = (from m in modules
                                    where m.M_ParentID == 0
                                    select new TreeNode
                                    {
                                        id = m.M_ID,
                                        app_id = app.A_ID,
                                        name = m.M_CName,
                                        type = 2,
                                        children = (from p in modules
                                                    where p.M_ParentID == m.M_ID
                                                    select new TreeNode
                                                    {
                                                        id = p.M_ID,
                                                        app_id = app.A_ID,
                                                        group_id = p.M_ParentID,
                                                        name = p.M_CName,
                                                        url = p.M_MoudleFormUrl,
                                                        type = 3
                                                    }).ToList()
                                    }).ToList()
                    });
                }
            }

            context.Response.Write(JSON.Instance.ToJSON(list));
        }
    }
}